import { useEffect, useState, useRef } from 'react';
import { viewUtils } from '@/utils/arcgis/index';
import { jsapi, geometryUtils } from '@/utils/arcgis';

type TStatus = undefined | 'pan' | 'rotate';

/**
 *  navigation toggle hook - navigation toggle逻辑抽成hook
*
 * @returns [status, pan, rotate, toggle] - 浏览工具状态，设置平移状态函数, 设置旋转状态函数, 切换函数
 
 * @author leway 
 * @date 2020-07-16
 * @beta
 */
function useNavigationToggle(): [undefined | 'pan' | 'rotate', () => void, () => void, () => void] {
  const [status, setStatus] = useState<TStatus>();
  const vmRef = useRef<any>();

  useEffect(() => {
    init();
  }, []);

  async function init() {
    const view = await viewUtils.isViewReady();
    const [NavigationToggleViewModel] = await jsapi.load([
      'esri/widgets/NavigationToggle/NavigationToggleViewModel',
    ]);
    vmRef.current = new NavigationToggleViewModel({ view });
    setStatus('pan');
  }

  function pan() {
    if (!vmRef.current) return;
    if (vmRef.current.navigationMode === 'pan') return;
    vmRef.current.toggle();
    setStatus('pan');
  }
  function rotate() {
    if (!vmRef.current) return;
    if (vmRef.current.navigationMode === 'rotate') return;
    vmRef.current.toggle();
    setStatus('rotate');
  }
  function toggle() {
    if (!vmRef.current) return;
    let nextStatus: TStatus = 'rotate';
    if (vmRef.current.navigationMode === 'rotate') {
      nextStatus = 'pan';
    }
    vmRef.current.toggle();
    setStatus(nextStatus);
  }

  return [status, pan, rotate, toggle];
}

export default useNavigationToggle;
